<?php
define('HOST', '127.0.0.1');
define('USER', 'root');
define('PASSWD', '801111');
define('PORT', '3306');
define('DB', 'gift');


##用于启动session，在以后的代码里无需显示启动session
session_start();

//检查有没有需要的参数
function request_params_exist($param_names) {
    foreach ($param_names as $name) {
        if (!isset($_POST[$name]) && !isset($_GET[$name])) {
            return false;
        }
    }
   return true;
}

//连接数据库
function db_connect() {
    $conn = @mysqli_connect(HOST, USER, PASSWD, DB, PORT) or die_db_link();
    $charset = 'utf8';
    mysqli_set_charset($conn, $charset) or die_db_error($conn, '字符集' . $charset . '设置失败');
    return $conn;
}

function die_db_error($conn) {
    $args = func_get_args();
    $num = count($args);
    $msg = mysqli_error($conn);
    if ($num > 1) {
        $msg = $args[1];
    }
    mysqli_close($conn);
    die(ret_error_json($msg));
}

function die_db_link() {
    $args = func_get_args();
    $num = count($args);
    $msg = $num === 0 ? '数据库连接失败' : $args[0];
    die(ret_error_json($msg));
}

// 用于其他情况的die
function die_error($message = '错误') {
    die(ret_error_json($message));
}

function die_fail($message = '失败') {
    die(ret_fail_json($message));
}

// 返回不同值的map
function ret_ok($data = null, $message = 'ok') {
    return array('status' => 'ok', 'message' => $message, 'data' => $data);
}

function ret_fail($message = 'fail') {
    return array('status' => 'fail', 'message' => $message, 'data' => null);
}

function ret_error($message = 'error') {
    return array('status' => 'error', 'message' => $message, 'data' => null);
}

// 返回不同值的json
function ret_ok_json($data = null, $message = 'ok') {
    return json_encode(ret_ok($data, $message), JSON_UNESCAPED_UNICODE);
}

function ret_fail_json($message = 'fail') {
    return json_encode(ret_fail($message), JSON_UNESCAPED_UNICODE);
}

function ret_error_json($message = 'error') {
    return json_encode(ret_error($message), JSON_UNESCAPED_UNICODE);
}

#######################################################################
define('USER_LOGGED', 'user');

// 检查是否登录
function is_logged() {
    return isset($_SESSION[USER_LOGGED]);
}

// 登录
function login($tel, $passwd, $table = 'user') {
    if ($tel === null || $tel == '' || $passwd == null || $passwd == '') {
        return ret_error('未传入电话号码或者密码');
    }

    // 检查数据库
    $tel1 = addslashes($tel); // 原来的电话号存session中
    $passwd1 = md5($passwd);
    $conn = db_connect();
    $result = mysqli_query($conn, "select * from $table where tel='$tel1' and passwd='$passwd1'") or die_db_error($conn);
    $sql = "select username from user where tel='$tel'";
    $username = mysqli_query($conn, $sql) or die_db_error($conn);
    $recs = mysqli_fetch_assoc($result);
    $count = count($recs);
    if ($count === 0) {
        die_fail('用户名不存在或者密码错误');
    }
    mysqli_close($conn);

    $_SESSION[USER_LOGGED] = array('id' => $recs['id'], 'tel' => $recs['tel'],'username'=>$recs['username']);
}

// 获取登录的用户名
function get_logged_username() {
    if (!is_logged()) {
        die_fail('未登录');
    }

    return $_SESSION[USER_LOGGED]['username'];
}

// 获取登录的用户id
function get_logged_userid() {
    if (!is_logged()) {
        die_fail('未登录');
    }

    return $_SESSION[USER_LOGGED]['id'];
}


// 注销
function logout() {
    if (!is_logged()) {
        die_fail('并未登录');
    }
    unset($_SESSION[USER_LOGGED]);
}

//显示错误页面
function show_error_page() {
    echo '<!DOCTYPE html>';
    echo '<html lang="zh-CN">';
    echo '<head lang="en">';
    echo '<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>Error!</title>
    <link rel="stylesheet" href="js/jquery/jquery.mobile-1.4.5.min.css"/>
    <link href="css/error.css" rel="stylesheet">
    </head>';
    echo '<body>
      <h2 class="font">您还未登录！</h2>
      <a href="login.html"><button type="button" class="btn">返回登录</button></a>
      <script src="js/jquery/jquery-1.12.0.min.js"></script>
        <script src="js/jquery/jquery.mobile-1.4.5.min.js"></script>
      </body>';
    echo '</html>';
}

#############################注册时##########################################
//判断用户名

function check_username($username) {

    $strlen = strlen($username);
    //两个字符以上，只能有中文，字母，数字，下划线 
        
    if (!preg_match("/^[a-zA-Z0-9_\x7f-\xff]+$/", $username)) {
        die_error('请输入正确格式的用户名');
    }
    if (20 < $strlen || $strlen < 2) {
        die_error('用户名长度为2-20之间');
    }
}

//判断密码
function check_passwd($passwd) {

    $strlen = strlen($passwd);
    //两个字符以上，只能有中文，字母，数字，下划线
    if (!preg_match("/^[A-Za-z0-9_]/", $passwd)) {
        die_error('密码只能由大小写字母、数字和下划线组成');
    }
    if (20 < $strlen || $strlen < 6) {
        die_error('密码长度在6—20之间');
    }
}

//判断手机号
function check_tel($tel) {
    if (!preg_match("/^1[34578]\d{9}$/", $tel)) {
        die_error('手机号输入有误，请输入正确格式手机号');
    }
    $conn = db_connect();
    $sql = "select * from user where tel='$tel'";
    $result = mysqli_query($conn, $sql) or die_db_error($conn);
    $num = mysqli_num_rows($result);
    if ($num != 0) {
        die_error('该用户号码已注册过');
    }
}


//判断两次密码是否相同
function check_passwd_isame($passwdone, $passwdtwo) {
    //$char_ret = "两次密码相同";
    if ($passwdone != $passwdtwo) {
        die_error('两次输入密码不一致');
    }
}

//往数据库添加用户
function create($username, $passwd, $tel) {
    $conn = db_connect();
    $sql1 = "select * from user";
    $result = mysqli_query($conn, $sql1) or die_db_error($conn);
    $num = mysqli_num_rows($result);
    $sql = "insert into user (id,username,passwd,tel) values ($num+1,'$username',md5('$passwd'),'$tel')";
    if (!mysqli_query($conn, $sql)) {
        die_db_error($conn);
    }
    mysqli_close($conn);
}
#################################################################################
//显示标签

//标签分类数
function labelsort_num(){
    $conn=db_connect();
    $sql = "select * from labelsort";
    $result = mysqli_query($conn, $sql) or die_db_error($conn);
    $num = mysqli_num_rows($result);
    return $num;
    mysqli_close($conn);
}

//标签分类名
function labelsort_name(){
    $conn=db_connect();
    $sql = "select sortname from labelsort";
    $result = mysqli_query($conn, $sql) or die_db_error($conn);
    $sortname=array();
    while($rows=mysql_fetch_array($result))
    {
       $sortname[] = $rows;
    }
    return $sortname;
    mysqli_close($conn);
}

function label_num($id){
    $conn=db_connect();
    $sql1 = "select * from label where id='$id'";
    $result = mysqli_query($conn, $sql1) or die_db_error($conn);
    $num = mysqli_num_rows($result);
    
    mysqli_close($conn);
}

#################################################################################
// json操作
function to_json($obj) {
    return json_encode($obj, JSON_UNESCAPED_UNICODE);
}

function from_json($json) {
    return json_decode($json, true);
}
